const HttpUtil = {
    httpRequest(method, url, headers, resolve, reject) {
        let tempHraders = {
            "User-Agent": navigator.userAgent
        };
        if (headers !== null || headers !== undefined) {
            tempHraders = Object.assign({}, tempHraders, headers)
        }
        Util.httpRequest({
            method: method,
            url: url,
            headers: tempHraders,
            onload: resolve,
            onerror: reject
        });
    },
    /**
     *封装好的底层post请求，一般情况下不要直接调用，请使用对应的封装好的函数
     */
    _post(url, data, headers, resolve, reject) {
        let temp = {
            "Content-Type": "application/json"
        };
        if (headers !== null || headers !== undefined) {
            temp = headers;
        }
        Util.httpRequest({
            method: "POST",
            url: url,
            headers: temp,
            data: JSON.stringify(data),
            onload: resolve,
            onerror: reject
        });
    },
    post(url, data, headers) {
        return new Promise((resolve, reject) => {
            this._post(url, data, headers, (res) => {
                resolve(this._toData(res));
            }, (error) => {
                reject(error);
            });
        });
    },
    /**
     * 封装好的底层get请求
     */
    get(url) {
        return new Promise((resolve, reject) => {
            this.httpRequest("get", url, {
                "User-Agent": navigator.userAgent,
            }, (res) => {
                resolve(this._toData(res))
            }, (error) => {
                reject(reject(error))
            });
        });
    },
    //私有的，不应该外部访问到，调整相应结果中的res数据
    _toData(res) {
        const data = {
            body: res.responseText,
            res: res,
            status: res.status,
            responseType: res["RESPONSE_TYPE_JSON"],
            bodyJson: null,
            message: ""
        };
        try {
            if (data.responseType === "json") {
                data.bodyJson = JSON.parse(res.responseText);
            }
        } catch (e) {
            data.error = e;
            data.bodyJson = null;
            data.message = "检测到responseType是json,但转换json失败了";
            console.error(data);
        }
        return data;
    },
    /**
     *携带cookioie发起get请求
     * @param url
     * @param {string}cookie
     */
    getCookie(url, cookie) {
        return new Promise((resolve, reject) => {
            this.httpRequest("get", url, {
                "User-Agent": navigator.userAgent,
                "cookie": cookie
            }, (res => {
                resolve(this._toData(res));
            }), (error) => {
                reject(error);
            });
        });
    }
};